//
//  AMapPolygonsFactory.m
//  flutter_plugin_gdmap
//
//  Created by xiaoka on 2021/9/27.
//

#import "AMapPolygonsFactory.h"
#import "MyConstant.h"
#import "FlutterPluginGdmapPlugin.h"
#import "AMapPolygonsHandle.h"


@implementation AMapPolygonsFactory

- (NSObject <FlutterMessageCodec> *)createArgsCodec {
    return [FlutterStandardMessageCodec sharedInstance];
}

- (NSObject <FlutterPlatformView> *)createWithFrame:(CGRect)frame
                                     viewIdentifier:(int64_t)viewId
                                          arguments:(id _Nullable)args {
    
    AMapPolygonsView *view = [[AMapPolygonsView alloc] initWithFrame:frame
                                      viewIdentifier:viewId];
    return view;
}

@end

@implementation AMapPolygonsView {
    CGRect _frame;
    int64_t _viewId;
    FlutterMethodChannel *_channel;
    MAMapView *_mapView;
    AMapSearchAPI * _search;//搜索对象
    FlutterResult _result;
    
    AMapGeoPoint * _realLocation;//最新坐标位置
    BOOL _firstLoad;
}

- (instancetype)initWithFrame:(CGRect)frame
               viewIdentifier:(int64_t)viewId {
    self = [super init];
    if (self) {
        _frame = frame;
        _viewId = viewId;
        _firstLoad = NO;
        _mapView = [[MAMapView alloc] initWithFrame:_frame];
        [self setup];
    }
    return self;
}

- (UIView *)view {
    return _mapView;
}

- (void)setup {
    NSLog(@"~~~~~控件初始化");
    //region 初始化地图配置, 跟android一样, 不能在view方法里设置, 不然地图会卡住不动, android端是直接把AMapOptions赋值到MapView就可以了
    // 尽可能地统一android端的api了, ios这边的配置选项多很多, 后期再观察吧
    
    [AMapServices sharedServices].enableHTTPS = YES;
    
    ///地图类型
    _mapView.mapType = MAMapTypeStandard;
    ///缩放等级
    _mapView.zoomLevel = 17;
    ///显示实时交通状况
    _mapView.showTraffic = NO;
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;

    ///自定义定位小蓝点
    MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
    r.showsAccuracyRing = NO;///精度圈是否显示，默认YES
    r.showsHeadingIndicator = NO;///是否显示方向指示(MAUserTrackingModeFollowWithHeading模式开启)。默认为YES
    r.enablePulseAnnimation = YES;///内部蓝色圆点是否使用律动效果, 默认YES
    //    r.image = [UIImage imageNamed:@"common_icon_location_blue"]; ///定位图标, 与蓝色原点互斥 不能设置大小～先用默认的图标
    [_mapView updateUserLocationRepresentation:r];
    
    ///控件交互
    _mapView.showsCompass= NO; // 设置成NO表示关闭指南针；YES表示显示指南针
    _mapView.showsScale= NO;  //设置成NO表示不显示比例尺；YES表示显示比例尺
    
    _mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    
    _channel = [FlutterMethodChannel methodChannelWithName:[NSString stringWithFormat:@"%@%lld",
                                                            [AMAP_CHANNEL_NAME stringByAppendingString:@"/amap_polygon"], _viewId]
                                           binaryMessenger:[FlutterPluginGdmapPlugin registrar].messenger];
    
    __weak __typeof__(self) weakSelf = self;
    [_channel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
        self->_result = result;
        if (weakSelf) {
            [weakSelf handleMethodCall:call result:result];
        }
    }];
    [self initSearch];
}

/// serach初始化
- (void)initSearch{
    _search =[[AMapSearchAPI alloc] init];
    _search.delegate = self;
}


- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    _mapView.delegate = self;
    // 设置围栏
    if ([@"drawPolygon" isEqualToString:call.method]) {
        // 清除围栏
//        [_mapView removeOverlays:[_mapView overlaysInLevel:MAOverlayLevelAboveRoads]];
        _firstLoad =YES;
        [AMapPolygonsHandle handleDrawPolygon:call.arguments mapView:_mapView];
        
        result(@(YES));
    }
    // 地图定位到给定的点
    else if ([@"goLocation" isEqualToString:call.method]) {
        // 地图控件内获取定位失败,获取flutter传过来的定位点
        NSData *locationData = [call.arguments[@"location"] dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *locationDic = [NSJSONSerialization JSONObjectWithData:locationData
                                                                    options:NSJSONReadingMutableContainers
                                                                      error:nil];
        CLLocationCoordinate2D coord = CLLocationCoordinate2DMake([[locationDic objectForKey:@"latitude"] doubleValue],
                                                                  [[locationDic objectForKey:@"longitude"] doubleValue]);
        [_mapView setCenterCoordinate:coord animated:YES];
        result(@"设置给定的点成功");
    }
    // 将屏幕中心定位到围栏内
    else if ([@"polygonInside" isEqualToString:call.method]) {
        
        [AMapPolygonsHandle handlePolygonInside:call.arguments mapView:_mapView];
        result(@"将屏幕中心定位到围栏内成功");
    }
    // 设置地图的手势开关
    else if ([@"setAllGestures" isEqualToString:call.method]) {
        BOOL isEnabled = [[call.arguments objectForKey:@"isEnabled"] boolValue];
        _mapView.userInteractionEnabled = isEnabled;
        result(@"设置地图的手势开关成功");
    }
    // 设置地图的缩放比例 地图的缩放级别一共分为 17 级，从 3 到 19。数字越大，展示的图面信息越精细。
    else if ([@"setZoomTo" isEqualToString:call.method]) {
        NSInteger num = [[call.arguments objectForKey:@"num"] integerValue];
        [_mapView setZoomLevel:num animated:YES];
        result(@"设置地图的缩放比例成功");
    }
    else {
        result(FlutterMethodNotImplemented);
    }
}

/// 位置搜索
/// @param coor 经纬度
- (void)getLocationSearch:(CLLocationCoordinate2D)coor {
    AMapPOIAroundSearchRequest  *request=[[AMapPOIAroundSearchRequest alloc] init];
    
    request.types = @"汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施|通行设施";
    request.page = 1;
    request.offset = 10;
    request.sortrule=0;
    request.location = [AMapGeoPoint locationWithLatitude:coor.latitude longitude:coor.longitude];
    request.radius=10000;
    _realLocation=[AMapGeoPoint locationWithLatitude:coor.latitude longitude:coor.longitude];
    [_search AMapPOIAroundSearch:request];
}

#pragma mark - MAMapViewDelegate
/**
 * @brief 根据overlay生成对应的Renderer
 * @param mapView 地图View
 * @param overlay 指定的overlay
 * @return 生成的覆盖物Renderer
 */
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolygon class]]) {
        MAPolygonRenderer *polylineRenderer = [[MAPolygonRenderer alloc] initWithPolygon:overlay];
        polylineRenderer.lineWidth = 4.f;
        polylineRenderer.strokeColor = [CommonUtility colorWithHexString:@"#0288FF"];
        polylineRenderer.fillColor = [UIColor colorWithRed:2/255.0 green:136/255.0 blue:255/255.0 alpha:0.4];
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.miterLimit = 0;
        return polylineRenderer;
    }
    return nil;
}

/**
 * @brief 地图移动结束后调用此接口
 * @param mapView       地图view
 * @param wasUserAction 标识是否是用户动作
 */
- (void)mapView:(MAMapView *)mapView mapDidMoveByUser:(BOOL)wasUserAction {
    if (_firstLoad) {
        _firstLoad = NO;
        return;
    }
    [self getLocationSearch:mapView.centerCoordinate];
}


#pragma mark -
/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    if (response.pois.count == 0){
        [_channel invokeMethod:@"getLocation" arguments:@""];
    }else{
        AMapPOI *poi = response.pois.firstObject;
        NSMutableDictionary *poiDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       poi.name,@"aoiName",
                                       poi.address,@"address",
//                                       [NSNumber numberWithDouble:poi.location.longitude],@"longitude",
//                                       [NSNumber numberWithDouble:poi.location.latitude],@"latitude",
                                       //用POI搜索结果的经纬度会导致在围栏内搜索到的点在围栏外，所以这里用原始点
                                       [NSNumber numberWithDouble:_realLocation.longitude],@"longitude",
                                       [NSNumber numberWithDouble:_realLocation.latitude],@"latitude",
                                       poi.city,@"city",
                                                nil];
            
        NSData *data = [NSJSONSerialization dataWithJSONObject:poiDic options:NSJSONWritingPrettyPrinted error:nil];
        NSString *poiStr = [[NSMutableString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"搜索json字符串:%@", poiStr);
        [_channel invokeMethod:@"getLocation" arguments:poiStr];
        
    }
}


@end
